package com.xzq.service;


import com.xzq.pojo.Result;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Service
public class ImageService {

    private static int LEFT_WIDTH=184;
    private static int RITHT_WIDTH=346;
    private static int TOP_HEIGHT=150;
    private static int DOWN_HEIGHT=370;


    /**
     *      页面: 用表单提交 ,将图片文件上传
     *
     *       服务器:  1,用这个专门处理图片得流 ImageIO 读取图片文件
     *               2, 通过ImageIo 得两个方法 ,getWith()  getHeight() 得到宽高,意味这拿到了这张图片上所有像素点得坐标
     *               3, 通过一个二维数组  ,索引充当坐标 ,该像素点的RGB充当值  这样做就可以对这个图片进行遍历操作每一个像素点
     *               4, 遍历二维数组  拿到每一个像素点
     *               5, 判断这个像素点的rgb值是否复合脑域写的条件 ,如果符合, 就通过ImageIo这个流里面的setRgb()这个方法
     *               6, setRgb(x,y,rgb值)  x,y就是像素点的横纵坐标, 再传一个红色的rgb值,这样就可以把这张图片符合条件的像素点rgb值替换

     * @param file
     * @param number
     * @param type
     * @param isSplit
     * @param request
     * @return
     */

    public Result splitImage(MultipartFile file, int number,String type,boolean isSplit, HttpServletRequest request) {
        //拿到服务器存储路径
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile");
        File folder = new File(realPath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        String cloneName=UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        String filePathName=UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile/" + newName;
        String clonePath=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile/" + cloneName;
        FileInputStream in = null;
        BufferedImage bi = null;
        BufferedImage splitclon = null;
        try {
            in = (FileInputStream) file.getInputStream();
            bi = ImageIO.read(in);
            if (isSplit) {
                splitclon = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
                splitclon.setData(bi.getData());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //处理bi图片,得到出血面积
        double redarea = 0d;

        if (isSplit) {
            //启用抠图
            handlerAutoSplit(splitclon, number);
            try {
                ImageIO.write(splitclon, "jpg", new File(folder,cloneName));
            } catch (IOException e) {
                System.out.println("自动抠图失败");
            }
        }

        if ("showArea".equals(type)) {
             redarea = handlerColorRgb_show(bi, number);
        } else if ("splitArea".equals(type)) {
             redarea = handlerColorRgb_split(bi, number);
        }
        redarea = handlerColorRgb_split(bi, number);
        //将该图片写入服务器中
        try {
            ImageIO.write(bi, "jpg", new File(folder,newName));
        } catch (IOException e) {
            System.out.println("图片转换错误");
        }
        System.out.println("图片服务器路径" + filePath);
        Result r = new Result();
        r.setFilePath(filePath);
        r.setArea(redarea);
        r.setClonePath(clonePath);
        return r;
    }

    //处理bi图片之区域
    private double handlerColorRgb_show(BufferedImage bi, int number) {

        int width=bi.getWidth();
        int height=bi.getHeight();
        Color real = new Color(255, 0, 0);
        System.out.println("宽度:"+width);
        System.out.println("高度:"+height);
        int [][] data=new int[width][height];
        double areaCount = 0d;
        for(int i=0;i<width;i++) {
            for (int j = 0; j < height; j++) {
                data[i][j] = bi.getRGB(i, j);
            }
        }
        //曾经的图 的条件 (((i > 55 && i < 142) || (i > 320 && i < 390)) && (j > 202 && j < 360) )
//        private static int LEFT_WIDTH=184;
//        private static int RITHT_WIDTH=346;
//        private static int TOP_HEIGHT=150;
//        private static int DOWN_HEIGHT=370;
        for(int i=0;i<width;i++) {
            for (int j = 0; j < height; j++) {
                if ((i > LEFT_WIDTH && i < RITHT_WIDTH)  && (j > TOP_HEIGHT && j < DOWN_HEIGHT) ) {
                    int srgb = data[i][j];
                    Color color = new Color(srgb);
                    int green = color.getGreen();
                    int red = color.getRed();
                    int blue = color.getBlue();
                    int thcolor = green + red + blue;
                    if (thcolor > 0 && thcolor < number) {
                        //bi : 这个图片得流  i :像素点得x坐标  j: 像素点得y坐标  real.getRGB() 红色得rgb值
                        bi.setRGB(i,j,real.getRGB());
                        areaCount++;
                    }
                }
            }
        }
        return areaCount / 38;
    }
    //处理bi图片之边界切割
    public double handlerColorRgb_split(BufferedImage bi, int number) {
        int width=bi.getWidth();
        int height=bi.getHeight();
        Color real = new Color(255, 0, 0);
        System.out.println("宽度:"+width);
        System.out.println("高度:"+height);
        int [][] data=new int[width][height];
        double areaCount = 0d;
        for(int i=0;i<width;i++) {
            for (int j = 0; j < height; j++) {
                data[i][j] = bi.getRGB(i, j);
            }
        }
        for(int i=0;i<width;i++) {
            for (int j = 0; j < height; j++) {
                if ((i > LEFT_WIDTH && i < RITHT_WIDTH)  && (j > TOP_HEIGHT && j < DOWN_HEIGHT)) {
                    int srgb = data[i][j];
                    int srgbCountRgb = computeRgb(srgb);
                    if (srgbCountRgb > 0 && srgbCountRgb < number) {
                        areaCount++;
                    }
                    //2,边界切割  逻辑 ,计算该像素点的上下左右
                    int up=data[i][j-1];
                    int upCountRgb=computeRgb(up);
                    int down=data[i][j+1];
                    int downCountRgb = computeRgb(down);
                    int left=data[i-1][j];
                    int leftCountRgb = computeRgb(left);
                    int right=data[i+1][j];
                    int rightCountRgb = computeRgb(right);
                    if ((upCountRgb > number && downCountRgb < number) || (upCountRgb < number && downCountRgb > number) || (leftCountRgb > number && rightCountRgb < number) || (leftCountRgb < number && rightCountRgb > number)) {
                        bi.setRGB(i,j,real.getRGB());
                    }

                }
            }
        }
        return areaCount / 38;
    }

    //自动抠图
    public void handlerAutoSplit(BufferedImage splitclon,int number) {
        int width=splitclon.getWidth();
        int height=splitclon.getHeight();
        Color black = new Color(0,0,0);
        Color real = new Color(255, 0, 0);
        Color write = new Color(255,255,255);
        System.out.println("宽度:"+width);
        System.out.println("高度:"+height);
        int [][] data=new int[width][height];
        for(int i=0;i<width;i++) {
            for (int j = 0; j < height; j++) {
                data[i][j] = splitclon.getRGB(i, j);
            }
        }
        for(int i=0;i<width;i++) {
            for (int j = 0; j < height; j++) {
                if ((i > LEFT_WIDTH && i < RITHT_WIDTH)  && (j > TOP_HEIGHT && j < DOWN_HEIGHT)  ) {
                    //1,区域整体显示
                    int srgb = data[i][j];
                    Color color = new Color(srgb);
                    int green = color.getGreen();
                    int red = color.getRed();
                    int blue = color.getBlue();
                    int thcolor = green + red + blue;
                    if (thcolor > 0 && thcolor < number) {
                        splitclon.setRGB(i,j,real.getRGB());
                    }else{
                        splitclon.setRGB(i,j,write.getRGB());
                    }
                }else{
                    splitclon.setRGB(i,j,write.getRGB());
                }

            }
        }
    }

    //计算rgbCount
    private  int computeRgb(int str) {
        Color color = new Color(str);
        return color.getGreen() + color.getRed() + color.getBlue();
    }
}
